<template>
  <div class="app-container tabs-content">
    <!--表格渲染-->
    <el-row style="display: flex;">
      <el-col :xs="24" :sm="24" :md="tableColSpan" :lg="tableColSpan" :xl="tableColSpan" style="margin-bottom: 10px">
        <!--工具栏-->
        <div class="head-container">
          <div v-if="crud.props.searchToggle">
            <!-- 搜索 -->
            <el-input v-model="query.blurry" clearable size="small" placeholder="子项号或子项名" style="width: 200px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
            <span v-if="advancedSearch">
              <el-select v-model="query.stage" clearable size="small" placeholder="阶段" style="width: 145px" class="filter-item" @change="crud.toQuery">
                <el-option v-for="(item,index) in dict.stage" :key="index" :label="item.label" :value="item.value" />
              </el-select>
              <el-select v-model="query.startStatus" clearable size="small" placeholder="启动状态" style="width: 145px" class="filter-item" @change="crud.toQuery">
                <el-option v-for="(item,index) in startStatusList" :key="index" :label="item.label" :value="item.value" />
              </el-select>
              <el-select v-model="query.runStatus" clearable size="small" placeholder="运行状态" style="width: 185px" class="filter-item" @change="crud.toQuery">
                <el-option v-for="(item,index) in runStatusList" :key="index" :label="item.label" :value="item.value" />
              </el-select>
            </span>
            <rrOperation :crud="crud" />

            <QueryToggle :isadvance="advancedSearch" @click.native="advancedSearch=!advancedSearch;searchButtonName=advancedSearch?'简单搜索':'高级搜索';handleCreate()" />
          </div>
          <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
          <crudOperation :permission="permission">
            <template slot="right">
              <el-dropdown class="filter-item">
                <el-button type="primary" size="mini" icon="el-icon-arrow-down">分享</el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item :disabled="crud.selections.length<1" @click.native="handleShare">分享</el-dropdown-item>
                  <el-dropdown-item @click.native="historyShare">历史分享</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <!-- 分享 -->
              <ShareCode ref="handleShareRef" :share-checkbox-params="shareCheckboxParams" @toQuerySub="toQuerySub" />
            </template>
          </crudOperation>
        </div>
        <!--表单组件-->
        <el-dialog append-to-body :close-on-click-modal="false" :before-close="crud.cancelCU" :visible="crud.status.cu > 0" :title="crud.status.title" width="700px">
          <el-form :key="'form' + isView()" ref="form" :inline="true" :model="form" :rules="rules" size="small" label-width="85px">
            <el-form-item label="子项号" prop="subNo">
              <el-col :span="24">
                <el-input v-model="form.subNo" v-viewinput="isView()" :maxlength="255" class="text-width1" :disabled="crud.form.subId!==null||isView()" />
              </el-col>
            </el-form-item>
            <el-form-item label="子项名" prop="subName">
              <el-col :span="24">
                <el-input v-model="form.subName" v-viewinput="isView()" :maxlength="255" class="text-width1" :disabled="isView()" />
              </el-col>
            </el-form-item>
            <el-form-item label="子项负责人" prop="inCharge">
              <el-col :span="24">
                <el-select v-model="form.inCharge" v-viewinput="isView()" filterable class="text-width1" :disabled="isView()">
                  <el-option
                    v-for="(item,index) in inChargeList"
                    :key="index"
                    :label="item.nickName"
                    :value="item.id"
                    :disabled="item.status===0 ? true:false"
                  />
                </el-select>
              </el-col>
            </el-form-item>
            <el-form-item label="工作量" required style="margin-bottom: 0">
              <el-col v-textwidth="isView()" :span="12">
                <el-form-item prop="workload">
                  <el-input-number v-model="form.workload" v-viewinput="isView()" :controls="false" :min="0" :max="9999999" :maxlength="10" class="text-width2" :disabled="isView()" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="workType">
                  <el-select v-model="form.workType" v-viewinput="isView()" filterable placeholder="请选择" class="text-width2" :disabled="isView()">
                    <el-option
                      v-for="(item,index) in dict.work_type"
                      :key="index"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-form-item>
            <el-form-item label="阶段" prop="stage">
              <el-col :span="24">
                <el-select v-model="form.stage" v-viewinput="isView()" filterable class="text-width1" :disabled="isView()">
                  <el-option
                    v-for="(item,index) in dict.stage"
                    :key="index"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-col>
            </el-form-item>
            <el-form-item label="运行状态" prop="runStatus">
              <el-col :span="24">
                <el-select v-model="form.runStatus" v-viewinput="isView()" filterable class="text-width1" :disabled="isView()">
                  <el-option
                    v-for="(item,index) in runStatusList"
                    :key="index"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-col>
            </el-form-item>
            <el-form-item label="产能" prop="capacity">
              <el-col :span="24">
                <el-input v-model="form.capacity" v-viewinput="isView()" :maxlength="255" class="text-width1" :disabled="isView()" />
              </el-col>
            </el-form-item>
            <el-form-item label="预计时间" required style="margin-bottom: 0">
              <el-col v-textwidth="isView()" :span="11">
                <el-form-item prop="estimateStart">
                  <el-date-picker v-model="form.estimateStart" v-viewinput="isView()" default-value="2024-08-24" :picker-options="pickerOptions" type="date" class="text-width2" :disabled="isView()" />
                </el-form-item>
              </el-col>
              <el-col class="line" :span="2" style="text-align: center;padding-top: 7px">~</el-col>
              <el-col :span="11">
                <el-form-item prop="estimateEnd">
                  <el-date-picker v-model="form.estimateEnd" v-viewinput="isView()" :picker-options="pickerOptions" type="date" class="text-width2" :disabled="isView()" />
                </el-form-item>
              </el-col>
            </el-form-item>
            <el-form-item label="涉及专业" prop="discipline">
              <el-col :span="24">
                <el-select v-model="disciplineDatas" v-viewinput:multselect="isView()" multiple filterable placeholder="请选择" class="text-width1" :disabled="isView()" @remove-tag="deleteDiscipline" @change="changeDiscipline">
                  <el-option
                    v-for="(item,index) in disciplineList"
                    :key="index"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-col>
            </el-form-item>
            <el-tooltip effect="dark" content="可选择范围来源于本项目人力资源中涵盖的'项目内专业'" placement="top-start">
              <el-button size="mini" type="text" icon="el-icon-warning" />
            </el-tooltip>
            <el-form-item label="工段设置" class="star">
              <el-button style="margin-bottom: 10px" icon="el-icon-plus" :disabled="isView()" @click="addWorkshopSection" />
              <div v-for="(item, index) in form.subWorkSectionList" :key="`d-${item.subId || item.newId}+sectionNo + ${index}`" style="width:535px;line-height: 38px;">
                <el-row v-if="!isView()" style="margin-bottom: 10px;">
                  <el-col :span="8">
                    <span v-if="item.isOnEdit">
                      <el-form-item
                        :key="`${item.subId || item.newId}+sectionNo`"
                        :prop="'subWorkSectionList.' + index + '.sectionNo'"
                        :rules="[
                          { required: true, message: '工段号不能为空', trigger: 'blur' },
                          { validator: validatePass, trigger: 'blur' }
                        ]"
                      >
                        <el-input v-model="item.sectionNo" v-viewinput="isView()" :disabled="!!item.sectionId" style="width: 176px" placeholder="输入工段号" maxlength="15" class="text-width1" show-word-limit />
                      </el-form-item>
                    </span>
                    <span v-else>{{ item.sectionNo }}</span>
                  </el-col>
                  <el-col :span="8">
                    <span v-if="item.isOnEdit">
                      <el-form-item
                        :prop="'subWorkSectionList.' + index + '.name'"
                        :rules="[
                          { required: true, message: '工段名称不能为空', trigger: 'blur' },
                          { required: true, message: '工段名称不能为空', trigger: 'change' }
                        ]"
                      >
                        <el-input v-model="item.name" v-viewinput="isView()" style="width: 176px" placeholder="输入工段名称" maxlength="50" class="text-width1" />
                      </el-form-item>
                    </span>
                    <span v-else>{{ item.name }}</span>
                  </el-col>
                  <!-- 操作按钮 -->
                  <el-col :span="8">
                    <div v-if="item.isOnEdit" class="s-operate">
                      <el-button type="text" @click="saveSection(item,index)">保存</el-button>
                      <el-button type="text" @click="cancelSection(item)">取消</el-button>
                    </div>
                    <div v-else class="s-operate">
                      <el-button type="text" @click="editSection(item)">编辑</el-button>
                      <el-button type="text" class="uifix-table-action-error-btn" @click="deleteSection(item)">删除</el-button>
                    </div>
                  </el-col>
                </el-row>

                <workSectionItem v-else :item="item" :index="index" />
                <!-- <el-row v-else class="section-row">
                  <el-col :span="3" class="title-col" style=""><span style="display:inline-block">{{ index==0?'工段号：':'' }}</span></el-col>
                  <el-col :span="6">{{ item.sectionNo }}</el-col>
                  <el-col :span="3" class="title-col"><span style="display:inline-block">{{ index==0?'工段名称：':'' }}</span></el-col>
                  <el-col :span="6">{{ item.name }}</el-col>
                  &lt;!&ndash; 操作按钮 &ndash;&gt;
                </el-row>-->

              </div>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button v-if="isView()" type="primary" @click="crud.cancelCU">关闭</el-button>
            <div v-else>
              <el-button @click="crud.cancelCU">取消</el-button>
              <el-popover
                v-if="crud.form.subId===null"
                ref="sure"
                placement="top"
                width="200"
              >
                <p>温馨提示：一旦提交,子项号便不可修改，请确认无误后提交！</p>
                <div style="text-align: right; margin: 0">
                  <el-button size="mini" type="text" @click="$refs['sure'].doClose()">取消</el-button>
                  <el-button type="primary" size="mini" @click="submitCrudForm">确定</el-button>
                </div>
                <el-button slot="reference" :loading="crud.status.cu === 2" type="primary">确认</el-button>
              </el-popover>
              <el-button v-else slot="reference" :loading="crud.status.cu === 2" type="primary" @click="submitCrudForm">确认</el-button>
            </div>
          </div>
        </el-dialog>
        <!--表格渲染-->
        <el-table ref="table" v-loading="crud.loading" stripe height="calc(100vh - 360px)" :data="crud.data" highlight-current-row style="width: 100%;" :row-class-name="rowClassName" @selection-change="crud.selectionChangeHandler" @current-change="handleCurrentChange">
          <el-table-column type="selection" width="50" />
          <el-table-column align="center" type="expand" width="30">
            <template slot-scope="props">
              <WorkSectionTable :table-data="props.row.subWorkSectionList" />
            </template>
          </el-table-column>
          <el-table-column prop="subNo" label="子项号" show-overflow-tooltip min-width="140">
            <template v-slot="{ row }">
              <template v-if="row.subNo !== '9999'">
                <el-link type="primary" @click="hanleView(row.subId)">{{ row.subNo }}</el-link>
              </template>
              <template v-else>{{ row.subNo }}</template>
            </template>
          </el-table-column>
          <el-table-column prop="subName" label="子项名" />
          <el-table-column prop="workType" label="工作量">
            <template slot-scope="scope">
              {{ scope.row.subNo === '9999' ? '' : scope.row.workload + '&nbsp;' + '/' + '&nbsp;' + dict.label.work_type[scope.row.workType] }}
            </template>
          </el-table-column>
          <el-table-column prop="stage" label="阶段" sortable>
            <template slot-scope="scope">
              {{ scope.row.subNo === '9999' ? '' : dict.label.stage[scope.row.stage] }}
            </template>
          </el-table-column>
          <el-table-column label="启动状态" sortable>
            <template slot-scope="scope">
              <div v-if="scope.row.subNo === '9999'">
                {{ scope.row.startStatus = '' }}
              </div>
              <div v-else>
                <el-tooltip slot="right" effect="dark" content="启动" placement="top-start">
                  <el-popover
                    v-if="!(scope.row.startStatus === 2)"
                    :ref="scope.$index"
                    placement="top"
                    width="200"
                  >
                    <p>确定启动吗？</p>
                    <div style="text-align: right; margin: 0">
                      <el-button size="mini" type="text" @click="$refs[scope.$index].doClose()">取消</el-button>
                      <el-button type="primary" size="mini" @click="start(scope.row.subId,scope.$index)">确定</el-button>
                    </div>
                    <el-button slot="reference" v-permission="permission.start" :disabled="(scope.row.project&&scope.row.project.startStatus!==2||scope.row.startStatus === 1||scope.row.startStatus === 2)" style="margin: 0 3px 0 0;" class="filter-item" size="mini" type="primary" icon="el-icon-caret-right" />
                  </el-popover>
                </el-tooltip>
                <el-tooltip slot="right" effect="dark" content="更新" placement="top-start">
                  <el-popover
                    v-if="scope.row.startStatus === 2"
                    :ref="scope.$index"
                    placement="top"
                    width="200"
                  >
                    <p>确定更新吗？</p>
                    <div style="text-align: right; margin: 0">
                      <el-button size="mini" type="text" @click="$refs[scope.$index].doClose()">取消</el-button>
                      <el-button type="primary" size="mini" @click="update(scope.row.subId,scope.$index)">确定</el-button>
                    </div>
                    <el-button slot="reference" v-permission="permission.start" :disabled="(scope.row.project.startStatus!==2||scope.row.updateStatus === 1||scope.row.updateStatus === 2)" style="margin: 0 3px 0 0;" class="filter-item" size="mini" type="warning" icon="el-icon-caret-right" />
                  </el-popover>
                </el-tooltip>
                <span v-show="scope.row.startStatus === 0||(scope.row.startStatus === 2&&scope.row.updateStatus === 0)">
                  <svg-icon icon-class="noStart" />
                </span>
                <span v-show="scope.row.startStatus===2 && scope.row.updateStatus === 2">
                  <svg-icon icon-class="success" />
                </span>
                <span v-show="scope.row.startStatus === -1||(scope.row.startStatus===2&&scope.row.updateStatus === -1)">
                  <svg-icon icon-class="exception" />
                </span>
                <span v-show="scope.row.startStatus === 1||(scope.row.startStatus===2&&scope.row.updateStatus === 1)">
                  <div style="display: inline-block;vertical-align: middle;">
                    <img :src="Starting" class="starting" name="number2">
                  </div>
                </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="runStatus" label="运行状态" :formatter="formatRunStatus" sortable />

          <el-table-column prop="inspectStatus" label="审查状态" sortable>
            <template slot-scope="{ row }">
              <el-tooltip placement="left">
                <div slot="content">
                  <p v-for="(item,key) in row.inspectSubList" :key="key" style="margin: 0;">
                    {{ item.reviewMonth }} / {{ item.declareNode }} / {{ item.inspectStatus }}
                  </p>
                </div>
                <span>{{ row.inspectStatus }}</span>
              </el-tooltip>
            </template>
          </el-table-column>

          <el-table-column v-if="checkPer(['admin','project:edit','project:del','permission:upload','permission:share'])" label="操作" align="center" width="220px">
            <template slot-scope="scope">
              <udOperation
                msg="确定删除本条数据及进度管理中的相关数据吗？"
                v-if="scope.row.startStatus === 1||scope.row.updateStatus === 1||scope.row.subNo === '9999'"
                :key="scope.row.startStatus + scope.row.updateStatus + scope.row.subNo"
                :data="scope.row"
                :permission="permission"
                :disabled-edit="scope.row.startStatus === 1 || scope.row.startStatus === 2 || scope.row.subNo === '9999' "
                :disabled-dle="scope.row.startStatus === 1 || scope.row.startStatus === 2 || scope.row.subNo === '9999'"
              >
                <template v-slot:right>
                  <el-button v-show="buttonList.indexOf('coordinates')!==-1&&scope.row.subNo==='9999'" size="mini" type="text" style="margin-left: 0" @click="coordinatesSet(scope.row);"><svg-icon icon-class="projectBase" class="uifix-svg" /> 项目基点</el-button>
                  <el-button v-show="buttonList.indexOf('coordinates')!==-1&&scope.row.subNo!=='9999'" size="mini" type="text" style="margin-left: 0" @click="coordinatesSet(scope.row);"><svg-icon icon-class="coordinatesSet" class="uifix-svg" /> 相对坐标</el-button>
                  <el-button v-if="buttonList.indexOf('toHub')!==-1" size="mini" type="text" style="margin-left: 0" :disabled="ifCoordinatesAdded(scope.row)" @click="toHub(scope.row)"><svg-icon icon-class="ellipse" class="uifix-svg-hub" /> Hub</el-button>
                  <el-button v-if="buttonList.indexOf('share')!==-1" size="mini" type="text" style="margin-left: 0px" @click="getShare(scope.row)"><svg-icon icon-class="icon-share" class="uifix-svg-share" /> 分享 </el-button>
                </template>

              </udOperation>
              <udOperation
                msg="确定删除本条数据及进度管理中的相关数据吗？"
                v-else
                :key="scope.row.startStatus + scope.row.updateStatus + scope.row.subNo + 'common'"
                :data="scope.row"
                :permission="permission"
                :disabled-edit="scope.row.subNo === '9999'"
                :disabled-dle="scope.row.startStatus === 1 || scope.row.startStatus === 2 || scope.row.subNo === '9999'"
              >
                <template v-slot:right>
                  <el-button v-show="buttonList.indexOf('coordinates')!==-1&&scope.row.subNo!=='9999'" size="mini" type="text" style="margin-left: 0" @click="coordinatesSet(scope.row);"><svg-icon icon-class="coordinatesSet" class="uifix-svg" /> 相对坐标 </el-button>

                  <!-- </el-tooltip> -->
                  <el-button v-show="buttonList.indexOf('coordinates')!==-1&&scope.row.subNo==='9999'" size="mini" type="text" style="margin-left: 0" @click="coordinatesSet(scope.row);"><svg-icon icon-class="projectBase" class="uifix-svg" /> 项目基点</el-button>
                  <el-button v-if="buttonList.indexOf('toHub')!==-1" size="mini" type="text" style="margin-left: 0" :disabled="ifCoordinatesAdded(scope.row)" @click="toHub(scope.row)"><svg-icon icon-class="ellipse" class="uifix-svg-hub" /> Hub</el-button>
                  <el-button v-if="buttonList.indexOf('share')!==-1" size="mini" type="text" style="margin-left: 0px" @click="getShare(scope.row)"><svg-icon icon-class="icon-share" class="uifix-svg-share" /> 分享</el-button>
                </template>

              </udOperation>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <!-- 收缩按钮 -->
      <el-col :xs="24" :sm="24" :md="toggleColSpan" :lg="toggleColSpan" :xl="toggleColSpan" class="toggleIcon">
        <svg-icon :icon-class="isTableExpanded ? 'sub-circle' : 'sub-circle-rotate'" style="width: 2.8em;height: 2.8em;" @click="toggleTable" />
      </el-col>
      <!-- 子项分配 -->
      <el-col :xs="24" :sm="24" :md="memberColSpan" :lg="memberColSpan" :xl="memberColSpan">
        <projectMember ref="projectMember" :project-sub-list="crud.data" :proj-id="projId" :sub-no="subNo" :getdetail="getdetail" />
      </el-col>
    </el-row>
    <!--上传模型-->
    <el-dialog class="abow_dialog" view-crash-manage convert-record :close-on-click-modal="false" :title="childParams.title" :visible.sync="dialogVisible" :destroy-on-close="false">
      <UpLoadModel :child-params="childParams" @dialogClose="dialogClose" />
    </el-dialog>
    <!--查看模型转换状态-->
    <el-dialog class="abow_dialog" view convert-record :close-on-click-modal="false" :title="childParams.title" :visible.sync="showStatus" :destroy-on-close="false">
      <transfer-status ref="handleTransferStatus" :child-params="childParams" />
      <div slot="footer" class="dialog-footer">
        <el-button type="button" @click="showStatus=false">关闭</el-button>
      </div>
    </el-dialog>
    <el-dialog class="abow_dialog" view-coordinates convert-record :close-on-click-modal="false" :title="childParams.title" :visible.sync="coordinatesShow" :destroy-on-close="false" :before-close="handDialogClose">
      <general-coordinates ref="generalCoordinates" :child-params="childParams" :coordinates-show.sync="coordinatesShow" :coordinates-position="coordinatesPosition" :sub-positon="subPositon" :sub-no="subNo" @refreshSubInfo="refreshSubInfo" />
    </el-dialog>
    <!-- 分享 -->
    <ShareCode ref="shareRef" :share-operate-params="shareOperateParams" />
  </div>
</template>

<script>
import QueryToggle from '../../../components/UiFix/QueryToggle.vue'
import crudprojectSub, { detail, start, update, subLink, detailByNo, checkWorkSection } from '@/api/project/projectSub'
import { getProjectUser } from '@/api/system/user'
import { getDiscipline } from '@/api/project/humanRes'
import CRUD, { presenter, header, form } from '@brotherCrud/crud'
import rrOperation from '@brotherCrud/RR.operation'
import crudOperation from '@brotherCrud/CRUD.operation'
import udOperation from '@brotherCrud/UD.operation'
import { trimAllTab } from '@/utils'
import { validateFile } from '@/utils/validate'
import Starting from '@/assets/images/starting.gif'
import UpLoadModel from './upLoadModel'
import TransferStatus from './transferStatus'
import projectMember from './projectMember'
import GeneralCoordinates from './GeneralCoordinates'
import { mapGetters } from 'vuex'
import store from '@/store'
import { getToken } from '@/utils/auth'
let discipline = []
const defaultForm = { subId: null, subNo: null, subName: null, createBy: null, updateBy: null, createTime: null, updateTime: null, projId: null, inCharge: null, stage: null, runStatus: null, capacity: null, workType: null, workload: null, estimateStart: null, estimateEnd: null, discipline: null, linkStatus: null }
import { SetSubRowClassName } from '@haisum-cloud/ui-components/packages/utils'
import workSectionItem from '@haisum-cloud/ui-components/packages/WorkSectionTable/src/sectionItem'
export default {
  name: 'ProjectSub',
  components: { TransferStatus, rrOperation, crudOperation, udOperation, UpLoadModel, GeneralCoordinates, projectMember, QueryToggle, workSectionItem },
  dicts: ['work_type', 'stage', 'inspect_plan_status', 'access_type'],
  cruds() {
    if (JSON.parse(localStorage.getItem('projectObject')).projId) {
      return [
        CRUD({
          title: '子项',
          url: 'api/projectSub',
          idField: 'subId',
          query: { projId: JSON.parse(localStorage.getItem('projectObject')).projId, page: 0, size: 50000 },
          sort: 'subId,desc',
          crudMethod: { ...crudprojectSub },
          optShow: {
            add: true,
            edit: false,
            del: false,
            reset: true
          }
        })
      ]
    }
  },
  mixins: [
    presenter(),
    header(),
    form(function() {
      return Object.assign({ project: { projId: this.query.projId }}, defaultForm)
    })
  ],
  data() {
    const validateCode = (rule, value, callback) => {
      if (!value) {
        callback(new Error('子项号不能为空'))
      } else if (!validateFile(value)) {
        callback(new Error('子项号必须符合文件名命名规则'))
      } else if (value.indexOf('-') !== -1) {
        callback(new Error("子项号不能含有  ' - '"))
      } else if (/[()（）]/.test(value) && !this.crud.form.subId) {
        callback(new Error('新增子项号不能含有括号'))
      } else {
        this.form.subNo = trimAllTab(value, 'g')
        callback()
      }
    }
    const validateEstimateStart = (rule, value, callback) => {
      if (!value) {
        callback(new Error('预计开始时间不能为空'))
      } else {
        if (this.form.estimateEnd) {
          this.$refs.form.validateField('estimateEnd')
        }
        callback()
      }
    }
    const validateEstimateEnd = (rule, value, callback) => {
      if (!value) {
        callback(new Error('预计结束时间不能为空'))
      } else {
        if (!this.form.estimateStart) {
          callback(new Error('预计开始时间不能为空！'))
        } else if (Date.parse(this.form.estimateStart) > Date.parse(value)) {
          callback(new Error('预计结束时间不能小于预计开始时间！'))
        } else {
          callback()
        }
      }
    }
    return {
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }]
      },
      isTableExpanded: true,
      tableColSpan: 15,
      toggleColSpan: 1,
      memberColSpan: 8,
      currentRow: null,
      assistCompany: null,
      subNo: null,
      projId: null,
      searchButtonName: '高级搜索',
      advancedSearch: false,
      inChargeList: [], // 子项负责人
      disciplineList: [], // 涉及专业
      buttonNum: 3, // 操作栏显示几个按钮,buttonNum大于等于3时生效
      flag: false,
      subPositon: {},
      coordinatesPosition: {},
      coordinatesShow: false, // 显示项目基点
      choice: '', // 下拉框选中项
      buttonList: [], // 权限按钮数组
      showStatus: false, // 模型转换状态弹框显示
      dialogVisible: false,
      shareCheckboxParams: {
        type: Object,
        selectedLists: [], // 子项选中内容
        projCode: null // 项目编号
      },
      childParams: {
        title: '上传模型',
        type: Object,
        projectCode: '',
        subNo: '',
        subId: null // 项目基点新增参数
      },
      shareOperateParams: {
        type: Object,
        projCode: '',
        subCode: '',
        subId: null, // 项目基点新增参数
        projId: null
      },
      runStatusList: [
        { label: '进行中', id: 1, value: 1 },
        { label: '暂停', id: 2, value: 2 },
        { label: '完成', id: 3, value: 3 },
        { label: '废除', id: 4, value: 4 }
      ], // 运行状态
      startStatusList: [
        { label: '启动失败', id: 1, value: -1 },
        { label: '未启动', id: 2, value: 0 },
        { label: '启动中', id: 3, value: 1 },
        { label: '启动成功', id: 4, value: 2 }
      ], // 启动状态
      disciplineDatas: [], // 专业多选变量
      pageType: '', // 页面类型
      Starting: Starting, // 启动中图片
      rules: {
        subNo: [
          { required: true, validator: validateCode, trigger: 'blur' },
          { min: 1, max: 255, message: '长度在 1 到 255 个字符', trigger: 'blur' }
        ],
        subName: [
          { required: true, message: '子项名不能为空', trigger: 'blur' },
          { min: 1, max: 255, message: '长度在 1 到 255 个字符', trigger: 'blur' }
        ],
        workType: [
          { required: true, message: '工作量类型不能为空', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ],
        workload: [
          { required: true, message: '工作量不能为空', trigger: 'blur' }
        ],
        estimateStart: [
          { required: true, validator: validateEstimateStart, trigger: 'blur' }
        ],
        estimateEnd: [
          { required: true, validator: validateEstimateEnd, trigger: 'blur' }
        ],
        discipline: [
          { required: true, message: '涉及专业不能为空', trigger: 'blur' }
        ]
      },
      permission: {
        add: ['admin', 'project:add'],
        edit: ['admin', 'project:edit'],
        del: ['admin', 'project:del'],
        start: ['admin', 'project:start'],
        download: ['admin', 'project:download']
      },
      fetched: false
    }
  },
  computed: {
    ...mapGetters([
      'user'
    ])
  },
  created() {
    const row = JSON.parse(localStorage.getItem('projectObject'))
    this.query.projId = row.projId
    this.projId = row.projId
    this.assistCompany = row.assistCompany
    // 获取项目编号
    this.shareCheckboxParams.projCode = row.code
    if (row) {
      // 获取子项负责人
      this.hanleProjectUser()
      // 获取涉及专业
      this.hanleDiscipline()
    }
  },
  mounted() {
    this.highLightRow()
    this.timesumming()
    this.hanleDom()
    this.getButtonNum()
  },
  beforeDestroy() {
    clearInterval(this.timer)
  },
  destroyed() {
    clearInterval(this.timer)
  },
  methods: {
    rowClassName: SetSubRowClassName,
    validatePass(rule, value, callback) {
      const regex = /^[a-zA-Z0-9_]+$/
      if (value === '') {
        callback(new Error('工段号不能为空'))
      } else if (regex.test(value)) {
        // 判断是否跟其他的重复了
        const sameData = this.form.subWorkSectionList.filter(item => item.sectionNo === value)
        if (sameData.length > 1) {
          callback(new Error('工段号不能重复'))
        } else {
          callback()
        }
      } else {
        callback(new Error('只能输入字母、数字或下划线'))
      }
    },
    /* 确认提交*/
    submitCrudForm() {
      // 对工段需要做处理
      const subWorkSectionList = []
      Array.isArray(this.form.subWorkSectionList) && this.form.subWorkSectionList.forEach(singleSection => {
        // 不是保存状态的 如果是新的 需要删除
        if (singleSection.isOnEdit) {
          if (singleSection.sectionNo && singleSection.prevInfo) {
            Object.assign(singleSection, { ...singleSection.prevInfo })
            delete singleSection.prevInfo
            subWorkSectionList.push(singleSection)
          }
        } else {
          delete singleSection.newId
          delete singleSection.prevInfo
          delete singleSection.subId
          delete singleSection.isOnEdit
          delete singleSection.hasEdited
          subWorkSectionList.push(singleSection)
        }
      })
      this.form.subWorkSectionList = subWorkSectionList
      this.crud.submitCU()
      this.flag = true
    },
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh](crud) {
      // 获取数据前设置好接口地址
      if (this.$refs.projectMember) {
        this.$refs.projectMember.query.subId = ''
      }
      this.fetched = false
      return true
    },
    /* 刷新更新权限*/
    [CRUD.HOOK.afterRefresh](crud) {
      if (this.flag) {
        this.flag = false
      }
    },
    // 高亮显示
    highLightRow() {
      // currentRow 刷新前被点击行数据
      if (this.currentRow === null) return
      for (const item of this.crud.data) {
        if (item.subId === this.currentRow.subId) {
          this.$refs.table.setCurrentRow(item)
        }
      }
    },
    /* 新增提示*/
    refreshSubInfo(flag) {
      this.crud.refresh()
      if (flag) {
        this.crud.notify('项目基点添加成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
      } else {
        this.crud.notify('子项坐标添加成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
      }
    },
    /* 关闭弹框*/
    handDialogClose() {
      this.coordinatesShow = false
      this.$refs.generalCoordinates.clearValidate()
    },
    /* 判断是否输入过坐标*/
    ifCoordinatesAdded(row) {
      if (row.positionX !== undefined || row.positionY !== undefined || row.positionZ !== undefined || row.rotationAngle !== undefined) {
        return false
      } else {
        return true
      }
    },
    /* 显示项目基点界面*/
    coordinatesSet(row) {
      this.subPositon = {}
      const param = {
        id: row.subId
      }
      detail(param).then(data => {
        if (data) {
          if (this.ifCoordinatesAdded(data)) {
            this.subPositon = {}
          } else {
            this.subPositon = {
              positionX: data.positionX,
              positionY: data.positionY,
              positionZ: data.positionZ,
              rotationAngle: data.rotationAngle
            }
          }
        }
      })
      const params = {
        projId: row.project.projId,
        subNo: '9999'
      }
      detailByNo(params).then((data) => {
        if (data) {
          this.coordinatesPosition.positionX = data.positionX
          this.coordinatesPosition.positionY = data.positionY
          this.coordinatesPosition.positionZ = data.positionZ
          this.coordinatesPosition.rotationAngle = data.rotationAngle
        }
      })
      this.coordinatesShow = true
      this.childParams.subId = row.subId
      this.childParams.subNo = row.subNo
      this.subNo = row.subNo
      if (row.subNo === '9999') {
        this.childParams.title = '项目基点'
      } else {
        this.childParams.title = '子项坐标(相对值)'
      }
    },
    /* 获取下拉框点击项*/
    handleCommand(command) {
      this.choice = command
    },
    /* 获取按钮个数*/
    getButtonNum() {
      this.buttonList = []
      if (this.checkPer(['admin', 'project:edit'])) {
        this.buttonList.push('edit')
      }
      if (this.checkPer(['admin', 'project:del'])) {
        this.buttonList.push('del')
      }
      this.buttonList.push('coordinates')
      this.buttonList.push('toHub')
      // this.buttonList.push('upload')
      this.buttonList.push('share')
      /*  状态和HUB权限一样，涉及到顺序，单独提出来*/
      // this.buttonList.push('status')
      /* 后续按钮继续在下面添加，写法同上，顺序不能变*/
    },
    /* 转换状态页面获取项目编号、子项编号、页面名称*/
    getModelStatus(row) {
      this.showStatus = true
      this.childParams.title = '转换状态'
      this.$nextTick(() => {
        this.$refs.handleTransferStatus.getStatus(row)
      })
    },
    /* 上传模型页面获取项目编号、子项编号、页面名称*/
    getProjectInfo(row) {
      this.childParams.projectCode = row.project.code
      this.childParams.subNo = row.subNo
      this.dialogVisible = true
      this.childParams.title = '上传模型'
    },
    dialogClose(val) {
      this.dialogVisible = val
    },
    // 获取子项负责人
    hanleProjectUser() {
      const params = {
        id: this.projId
      }
      getProjectUser(params).then(data => {
        if (data) {
          this.inChargeList = data
        }
      })
    },
    // 获取涉及专业
    hanleDiscipline() {
      const params = {
        projId: this.projId
      }
      getDiscipline(params).then(data => {
        if (data) {
          this.disciplineList = data
        }
      })
    },
    // 点击行内分享
    getShare(row) {
      this.shareOperateParams.projId = row.project.projId
      this.shareOperateParams.subId = row.subId
      this.shareOperateParams.projCode = row.project.code
      this.shareOperateParams.subCode = row.subNo
      // 9999分享时不显示自定义
      if (row.subNo === '9999') {
        this.$refs.shareRef.accessTypeList = this.dict.access_type.filter(item => item.value !== '3')
      } else {
        this.$refs.shareRef.accessTypeList = this.dict.access_type
      }
      // 清空checkbox
      this.$refs.table.clearSelection()
      this.$refs.shareRef.open = true
    },
    // 分享
    handleShare() {
      // 获取选中的子项内容
      this.shareCheckboxParams.selectedLists = this.crud.selections
      // 打开分享设置弹框
      this.$refs.handleShareRef.open = true
      // 过滤 “显示内容”
      if (this.crud.selections.length > 1 || this.crud.selections.some(item => item.subNo === '9999')) {
        // 批量分享和9999不含自定义 单行分享包含
        this.$refs.handleShareRef.accessTypeList = this.dict.access_type.filter(item => item.value !== '3')
      } else {
        this.$refs.handleShareRef.accessTypeList = this.dict.access_type
      }
    },
    toQuerySub() {
      this.crud.toQuery()
    },
    // 历史分享
    historyShare() {
      // 打开历史分享弹框
      this.$refs.handleShareRef.openHistory = true
      // 获取历史分享
      this.$refs.handleShareRef.queryAllGroupBy()
    },
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form, type) {
      this.pageType = ''
      if (crud.form.subId === null) {
        form.startStatus = null
      } else {
        // 查看时
        if (type === 'view') {
          this.pageType = type
        }
        if (!type) {
          this.pageType = 'edit'
        }
        this.getdetail(form.subId)
        return true
      }
    },
    // 新增前
    [CRUD.HOOK.beforeToAdd]() {
      // 将多选的值设置为空
      this.disciplineDatas = []
      /* 清空项目基点属性*/
      delete this.form.positionX
      delete this.form.positionY
      delete this.form.positionZ
      delete this.form.rotationAngle
      // 复制
      if (this.crud.data.length > 0) {
        // 专业
        discipline = []
        const _this = this
        if (form.discipline !== null) {
          const software = JSON.parse(this.crud.data[0].discipline)
          if (software.length > 0) {
            software.forEach(function(item) {
              _this.disciplineDatas.push(item.id)
              const data = { id: item.id }
              discipline.push(data)
            })
          }
        }
        Object.assign(this.form, {
          subName: this.crud.data[0].subName,
          workload: this.crud.data[0].workload,
          workType: this.crud.data[0].workType,
          estimateStart: this.crud.data[0].estimateStart,
          estimateEnd: this.crud.data[0].estimateEnd,
          subWorkSectionList: []
        })
      }
    },
    // 初始化编辑时候的专业
    [CRUD.HOOK.beforeToEdit](crud, form) {
      // 将多选的值设置为空
      this.disciplineDatas = []
      discipline = []
      const _this = this
      if (form.discipline !== null) {
        const software = JSON.parse(form.discipline)
        if (software.length > 0) {
          software.forEach(function(item) {
            _this.disciplineDatas.push(item.id)
            const data = { id: item.id }
            discipline.push(data)
          })
        }
      }
    },
    [CRUD.HOOK.beforeValidateCU](crud) {
      crud.form.discipline = discipline
    },
    // 提交前做的操作
    [CRUD.HOOK.afterValidateCU](crud) {
      if (crud.form.subId === null) {
        this.$refs['sure'].doClose()// 关闭提交确认框
      }
    },
    // 点击高级搜索
    handleCreate() {
      this.crud.resetQuery()
    },
    addWorkshopSection() { // 添加一条工段信息
      // subWorkSectionList
      const newSection = { sectionNo: '', subId: this.form.subId, name: '', isOnEdit: true, newId: 'new_' + new Date().getTime() + Math.random() }// 设置虚拟ID，以便删除
      if (!Array.isArray(this.form.subWorkSectionList)) {
        this.form.subWorkSectionList = [newSection]
        this.$set(this.form, 'subWorkSectionList', [newSection])
      } else {
        this.form.subWorkSectionList.unshift(newSection)
      }
      this.$forceUpdate()
    },
    saveSection(row, index) {
      const vueObject = this
      this.$refs.form.validateField(`subWorkSectionList.${index}.sectionNo`, function(e) {
        // 判断是否有重复
        // 判断是否已经有重复值
        if (!vueObject.form.subId) { // 新增无SUBID不接口校验了,最后结果排除
          if (!e && row.name) {
          //  delete row.newId
            row.hasEdited = true
            vueObject.$set(row, 'isOnEdit', false)
          }
        } else {
          checkWorkSection({ subId: vueObject.form.subId, sectionNo: row.sectionNo, sectionId: row.sectionId || '' }).then(res => {
            if (!e && row.name) {
              // delete row.newId
              row.hasEdited = true
              vueObject.$set(row, 'isOnEdit', false)
            }
          }).catch(e => {
            console.error(e.response.data.message)
          })
        }
      })
    },
    deleteSection(row) {
      console.log(row)
      if (row.newId) { // 新增的删除
        this.form.subWorkSectionList = this.form.subWorkSectionList.filter(item => (!item.newId) || (item.newId !== row.newId))
      } else { // 取消的删除
        this.form.subWorkSectionList = this.form.subWorkSectionList.filter(item => (!item.sectionId) || (item.sectionId !== row.sectionId))
      }
      this.$forceUpdate()
    },
    editSection(row) {
      console.log(row)
      row.prevInfo = {
        name: row.name,
        sectionNo: row.sectionNo
      }
      this.$set(row, 'isOnEdit', true)
    },
    cancelSection(row) {
      if (row.newId && !row.hasEdited) {
        this.form.subWorkSectionList = this.form.subWorkSectionList.filter(item => !item.newId || item.newId !== row.newId)
      } else {
        const { name, sectionNo } = row.prevInfo
        row.name = name
        row.sectionNo = sectionNo
        this.$set(row, 'isOnEdit', false)
      }
      this.$forceUpdate()
    },
    // 是否查看
    isView() {
      if (this.pageType === 'view') {
        return true
      } else {
        return false
      }
    },
    // 是否编辑
    isEdit() {
      if (this.pageType === 'edit') {
        return true
      } else {
        return false
      }
    },
    // 查看
    hanleView(subId) {
      const findSub = this.crud.data.find(item => {
        return item.subId === subId
      })
      findSub && this.crud.toView(findSub, 'view')
      /* this.crud.data.map((item, index) => {
        if (item.subId === subId) {
          this.crud.toView(this.crud.data[index], 'view')
        }
      })*/
    },
    deleteDiscipline(value) {
      discipline.forEach(function(data, index) {
        if (data.id === value) {
          discipline.splice(index, value)
        }
      })
    },
    changeDiscipline(value) {
      discipline = []
      value.forEach(function(data) {
        const disciplineId = { id: data }
        discipline.push(disciplineId)
      })
    },
    // 启动子项
    start(id, index) {
      const params = {
        id: id
      }
      const api = start(params)
      api.then(object => {
        this.crud.notify('子项发起启动成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
        this.crud.data.map(function(item) {
          if (item.subId === id) {
            item.startStatus = 1
          }
        })
      })
      if (this.$refs[index]) {
        this.$refs[index].doClose()
      }
    },
    // 更细启动项目
    update(id, index) {
      const params = {
        id: id
      }
      const api = update(params)
      api.then(object => {
        this.crud.notify('子项发起更新成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
        this.crud.data.map(function(item) {
          if (item.subId === id) {
            item.updateStatus = 1
          }
        })
      })
      if (this.$refs[index]) {
        this.$refs[index].doClose()
      }
    },
    // 子项链接
    setLink(id) {
      const params = {
        id: id
      }
      subLink(params).then(() => {
        this.crud.notify('子项发起重新链接成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
        const thiz = this
        this.crud.data.forEach(function(item) {
          if (item.subId === id) {
            item.linkStatus = 1
            thiz.form.linkStatus = 1
          }
        })
      })
    },
    /* 取得项目状态*/
    getdetail(id) {
      const params = {
        id: id
      }
      detail(params).then(data => {
        if (data) {
          this.crud.data.forEach(function(item) {
            if (item.subId === id) {
              item.updateStatus = data.updateStatus
              item.startStatus = data.startStatus
              item.linkStatus = data.linkStatus
            }
          })
        }
      })
    },
    timesumming() {
      const _this = this
      clearInterval(_this.timer)
      this.timer = setInterval(() => {
        this.resetTime()
        var domlist = document.getElementsByName('number2')
        for (let i = 0; i < domlist.length; i++) {
          if (!this.time[i]) return
          if (this.time[i].startStatus !== 1 && this.time[i].updateStatus !== 1) {
            domlist.item(i).innerText = ''
          } else {
            this.getdetail(this.time[i].subId)
          }
        }
      }, 1000)
    },
    hanleDom() {
      setTimeout(() => {
        const domlist = document.getElementsByName('number2')
        this.resetTime()
        for (let i = 0; i < domlist.length; i++) {
          if (!this.time[i]) return
          this.getdetail(this.time[i].subId)
        }
      }, 1100)
    },
    // 选中子项后，设置子项分配
    handleCurrentChange(row) {
      this.highLightRow()
      if (row) {
        this.subNo = row.subNo
        this.$refs.projectMember.query.subId = row.subId
        this.$refs.projectMember.subId = row.subId
        this.$refs.projectMember.projectName = JSON.parse(localStorage.getItem('projectObject')).projName
        this.$refs.projectMember.getProjectDiscipline(row.subId)
        this.$refs.projectMember.hanleProjResource(row.project.projId)
        this.$refs.projectMember.hanleProjectMember(row.subId)
        // 清空复制数组
        this.$refs.projectMember.checkedRowList = []
        // 清空表格
        this.$refs.projectMember.form.projectMembers = []
        if (row.subNo === '9999') {
          return false
        } else {
          return true
        }
      }
    },
    /* 给time赋值*/
    resetTime() {
      this.time = this.crud.data
    },
    // 去hub
    toHub(row) {
      // 通过用户登录
      const token = getToken()
      // 如果hub退出了 那么这边就去登录页
      store.dispatch('GetInfo').then(() => { // 拉取user_info
        window.open(process.env.VUE_APP_HUB_Login + `?redirect=%2Fhub%2Fbrowse%3FprojId%3D${row.project.projId}%26subId=${row.subId}%26projectName=${encodeURIComponent(row.project.name)}%26subNo=${encodeURIComponent(row.subNo.replaceAll('&', '-').replaceAll('%', '|').replaceAll('#', '<').replaceAll('+', '>'))}%26subName=${encodeURIComponent(row.subName)}%26cname=model%26token=${token}`, 'HUB')
      }).catch(() => {})
    },
    // 信息同步
    informationSynchronization() {
      // const params = {
      //   id: this.user.id
      // }
      // userDesktopDetail(params).then(data => {
      //   if (data) {
      //     this.crud.notify(JSON.parse(localStorage.getItem('projectObject')).name + '，子项信息同步已完成，请查阅', CRUD.NOTIFICATION_TYPE.SUCCESS)
      //     this.crud.resetQuery()
      //   }
      // })
    },
    // 运行状态转换
    formatRunStatus(row) {
      let x = ''
      if (row.subNo === '9999') {
        return ''
      } else {
        switch (row.runStatus) {
          case 1:x = '进行中'
            break
          case 2:x = '暂停'
            break
          case 3:x = '完成'
            break
          case 4:x = '废除'
            break
        }
        return x
      }
    },
    // 收缩表格
    toggleTable() {
      if (this.tableColSpan === 15) {
        this.tableColSpan = 23
        this.memberColSpan = 0
        this.toggleColSpan = 1
        this.isTableExpanded = false
      } else {
        this.tableColSpan = 15
        this.memberColSpan = 8
        this.toggleColSpan = 1
        this.isTableExpanded = true
      }
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.tooltip-div{
  margin: 0;
  padding: 0;
  display: inline-block;
}
.toggleIcon{
  cursor: pointer;
  width: 41px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
 ::v-deep .el-input-number .el-input__inner {
    text-align: left;
  }
 ::v-deep .el-form-item--small .el-form-item__content {
   line-height: 18px;
 }
::v-deep .el-form-item {
  &.s-el-form-item{
    margin-bottom: 0;
}

  .text-width1{
    width: 536px;
    .el-input__inner{padding-right: 32px ;}
  }
  .text-width2{
    width: 218px
  }
  ::v-deep .el-table .cell{
    overflow: inherit;
  }
  ::v-deep .el-table__body-wrapper {
    overflow-y: auto;
    margin-top: 2px;
    height: 728px;
  }
  .s-operate{
    margin-left: 11px;
  }
}
::v-deep  .no-expand-row{
    .el-table__expand-icon{
        display: none;
      }
  }
  .section-row{
    margin-bottom: 10px; position: relative;margin-left: -85px;
    .title-col{
      box-sizing: border-box;
      width:85px; padding-right: 12px; text-align: right; color: var(--brother-common-table-empty-text-color); font-size: 14px; font-weight: 700
    }
  }
</style>
